<template>
  <div class="count-down">
    <span>{{ hours | addZero }}</span>
    <span>{{ minutes | addZero }}</span>
    <span>{{ seconds | addZero }}</span>
  </div>
</template>

<script>
export default {
  name: 'CountDown',
  data () {
    return {
      hours: 0,
      minutes: 0,
      seconds: 0
    }
  },
  filters: {
    addZero (num) {
      return num > 10 ? num : '0' + num
    }
  },
  props: {
    startTime: String,
    endTime: String
  },
  created () {
    const timeDefference = this.getTimeDifference()
    this.getCountDown(timeDefference)
    this.timer = setInterval(() => {
      const timeDefference = this.getTimeDifference()
      this.getCountDown(timeDefference)
    }, 1000)
  },
  beforeDestroy () {
    clearInterval(this.timer)
  },
  methods: {
    getTimeDifference () {
      return (new Date(this.endTime).valueOf() - new Date().valueOf()) / 1000
    },
    getCountDown (time) {
      const [hours, minutes, seconds] = [
        ~~(time / 3600),
        ~~((time % 3600) / 60),
        ~~((time % 3600) % 60)
      ]
      this.hours = hours
      this.minutes = minutes
      this.seconds = seconds
    }
  }
}
</script>

<style lang="scss">
.count-down {
  display: inline-block;
  width: 2.7027rem;

  span {
    align-items: center;
    position: relative;
    width: 0.4054rem;
    height: 0.4054rem;
    margin-left: 0.2162rem;
    color: #fff;
    background: rgb(251, 59, 41);
    font-size: 12px;
    text-align: center;
    border-radius: 0.1541rem;

    &:nth-child(-n + 2)::after {
      position: absolute;
      top: 50%;
      right: -0.1622rem;
      content: ':';
      color: rgb(251, 59, 41);
      font-weight: 700;
      transform: translateY(-50%);
    }
  }
}
</style>
